import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ApiException } from 'src/common/exceptions/api.exception';
import { Repository } from 'typeorm';
import Category from 'src/entities/admin/sys-category.entity';
import {
  CreateCategoryDto,
  UpdateCategoryDto,
  DelCategories,
  ListCategoryDto,
} from './category.dto';
@Injectable()
export class SysCategoryService {
  constructor(
    @InjectRepository(Category)
    private readonly categoryRepository: Repository<Category>,
  ) {}

  /**
   * 添加分类
   * @param Category
   */
  async create(category: CreateCategoryDto) {
    const { name, type } = category;
    const existCategory = await this.categoryRepository.findOne({
      where: { name },
    });

    if (existCategory) {
      throw new ApiException(12001);
    }
    const categoryObj = new Category();
    categoryObj.name = name;
    categoryObj.type = type;
    const newCategory = await this.categoryRepository.save(categoryObj);
    return newCategory;
  }

  /**
   * 获取所有分类
   */
  async findAll(queryParams): Promise<Category[]> {
    const { name, type, page, limit } = queryParams;
    const qb = this.categoryRepository
      .createQueryBuilder('category')
      .where('category.name=:name', { name })
      .orWhere('category.type=:type', { type })
      .skip((page - 1) * limit)
      .take(limit)
      .orderBy('category.created_at', 'ASC');

    const data = await qb.getMany();
    return data;
  }

  /**
   * 获取指定分类
   * @param id
   */
  async findById(id): Promise<Category> {
    const data = await this.categoryRepository
      .createQueryBuilder('category')
      .where('category.id=:id')
      .orWhere('category.name=:id')
      .orWhere('category.type=:id')
      .setParameter('id', id)
      .getOne();

    return data;
  }

  async findByIds(ids): Promise<Array<Category>> {
    return this.categoryRepository.findBy({ id: ids });
  }

  /**
   * 更新分类
   * @param id
   * @param Category
   */
  async updateById(category): Promise<Category> {
    const oldCategory = await this.categoryRepository.findOne({ where: { id: category.id } });
    const updatedCategory = await this.categoryRepository.merge(oldCategory, category);
    return this.categoryRepository.save(updatedCategory);
  }

  /**
   * 删除分类
   * @param id
   */
  async deleteById(id) {
    try {
      const category = await this.categoryRepository.findOne({ where: { id } });
      await this.categoryRepository.remove(category);
      return true;
    } catch (e) {
      throw new ApiException(12000);
    }
  }
}
